package com.lx.user.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lx.bean.Result;
import com.lx.bilibili.entity.User;
import com.lx.bilibili.util.QRCodeGenerator;
import com.lx.user.dao.UserMapper;
import com.lx.user.web.respository.TokenKvRepository;
import com.lx.user.web.respository.dos.TokenDo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RequestMapping("/pc")
@RestController
@CrossOrigin(maxAge = 3600)
public class PcController {

    @Autowired
    TokenKvRepository tokenKvRepository;

    @Autowired
    UserMapper userMapper;

    @GetMapping("/qrLogin")
    public String loginPage() {
        return "rqLogin";
    }

    @GetMapping("/qrCode")
    public ResponseEntity<byte[]> qrCode() {
        String code = UUID.randomUUID().toString();
        // 二维码code 在websocket里面保存
        System.out.println("code = " + code);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_PNG)
                .body(QRCodeGenerator.generate(code));
    }

    @RequestMapping("loginByImageCode")
    public Result loginByImageCode(String token) {
        TokenDo tokenDo = tokenKvRepository.get(token);
        if (tokenDo == null) {
            throw new IllegalArgumentException("token 已过期");
        }
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        System.out.println("tokenDo = " + tokenDo);
        lqw.eq(User::getName, tokenDo.getUserName());
        lqw.eq(User::getPassword, tokenDo.getPassword());
        return new Result(1, "登陆成功", userMapper.selectOne(lqw));
    }

//    public void loginByImageCode() {
//        User user = new User();
//        Object o = user;
//        User user1 = (User) o;
//    }
}
